package com.crpc.core.loadBalance.impl;

import com.crpc.common.crpcEnum.CrpcExceptionEnums;
import com.crpc.common.exception.CrpcException;
import com.crpc.core.loadBalance.AbstractLoadBalance;
import com.crpc.core.loadBalance.Selector;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author wzy
 * @version 1.0
 * @description: 轮训负载均衡策略
 * @date 2023/9/30 21:29
 */
@Slf4j
public class RoundRobinLoadBalance extends AbstractLoadBalance {

    @Override
    public Selector getSelector(List<InetSocketAddress> inetSocketAddressList) {
        Selector selector = new RoundRobinSelector(inetSocketAddressList);
        return selector;
    }

    private static class RoundRobinSelector implements Selector {
        private List<InetSocketAddress> socketAddressList;
        private AtomicInteger integer;

        public RoundRobinSelector(List<InetSocketAddress> socketAddressList) {
            this.socketAddressList = socketAddressList;
            this.integer = new AtomicInteger(0);
        }

        @Override
        public InetSocketAddress getNext() {
            if (socketAddressList == null || socketAddressList.isEmpty()) {
                log.error("负载均衡时服务信息列表为空");
                throw new CrpcException(CrpcExceptionEnums.LOAD_BALANCE_ERROR);
            }
            InetSocketAddress address = socketAddressList.get(integer.get());
            if (integer.get() == socketAddressList.size() - 1) {
                integer.set(0);
            } else {
                integer.incrementAndGet();
            }
            return address;
        }

    }
}
